//
//  Register.m
//  Speedater
//
//  Created by NgoThang on 12/29/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "Register.h"
#import "AGB.h"
#import "PrivacyPolicy.h"
#import "AppDelegate.h"
#import "JSON.h"

@interface Register (Private)

- (void)cleanup;

@end

@implementation Register (Private)

- (void)cleanup
{
    self.myScrollView = nil;
    self.lightImageView = nil;
    self.avatarImageView = nil;
    self.lightRedButton = nil;
    self.lightYellowButton = nil;
    self.lightGreenButton = nil;
    self.pickImageButton = nil;
    self.acceptTACButton = nil;
    self.submitButton = nil;
    self.usernameTextField = nil;
    self.passwordTextField = nil;
    self.emailTextField = nil;
    self.genderLabel = nil;
    self.searchGenderLabel = nil;
    self.agbLabel = nil;
    self.privacyPolicyLabel = nil;
}

@end


@implementation Register

@synthesize myScrollView;
@synthesize lightImageView, avatarImageView;
@synthesize lightRedButton, lightYellowButton, lightGreenButton, pickImageButton, acceptTACButton, submitButton;
@synthesize usernameTextField, passwordTextField, emailTextField;
@synthesize genderLabel, searchGenderLabel, agbLabel, privacyPolicyLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    //NSLog(@"REGISTER -> dealloc");
    [self cleanup];
    [super dealloc];
}

#pragma mark -
#pragma mark - Custom functions

- (void)hideKeyBoard
{
    [self.usernameTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    [self.emailTextField resignFirstResponder];
}

- (IBAction)lightRedButtonClick:(id)sender
{
    trafficLightInt = 0;
    [self.lightImageView setImage:[UIImage imageNamed:@"light_red.png"]];
}

- (IBAction)lightYellowButtonClick:(id)sender
{
    trafficLightInt = 1;
    [self.lightImageView setImage:[UIImage imageNamed:@"light_yellow.png"]];
}

- (IBAction)lightGreenButtonClick:(id)sender
{
    trafficLightInt = 2;
    [self.lightImageView setImage:[UIImage imageNamed:@"light_green.png"]];
}

- (void)showActionSheet3
{
    // hide keyboard first
    [self hideKeyBoard];
    
    // show action
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:nil];
    
    
    [actionSheet addButtonWithTitle:@"Photo-Bibliothek"];
    [actionSheet addButtonWithTitle:@"Gespeicherte Fotoalbum"];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        [actionSheet addButtonWithTitle:@"Kamera"];
    [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
    [actionSheet release];
}

- (IBAction)pickImageButtonClick:(id)sender
{
    [self showActionSheet3];
    curentTargetControl = pickImageButton;
}

- (IBAction)acceptTACButtonClick:(id)sender
{
    if (acceptTACButton.isSelected)
        [acceptTACButton setSelected:NO];
    else
        [acceptTACButton setSelected:YES];
}

- (BOOL)validateFields
{
    if(trafficLightInt < 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:nil 
                              message:NSLocalizedString(@"Please choose an Ampel value!", nil) 
                              delegate:nil 
                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                              otherButtonTitles:nil];
        [alert show];	
        [alert release];
        return NO;   
    }
    if(![usernameTextField.text length])
    {
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:nil 
                              message:NSLocalizedString(@"Please enter your username!", nil) 
                              delegate:nil 
                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                              otherButtonTitles:nil];
        [alert show];	
        [alert release];
        return NO;   
    }
    if(![passwordTextField.text length])
    {
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:nil 
                              message:NSLocalizedString(@"Please enter your password!", nil) 
                              delegate:nil 
                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                              otherButtonTitles:nil];
        [alert show];	
        [alert release];
        return NO;   
    }
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    BOOL isValid = [emailTest evaluateWithObject:emailTextField.text];
    if(![emailTextField.text length] || !isValid)
    {
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:nil 
                              message:NSLocalizedString(@"Please enter your email address!", nil) 
                              delegate:nil 
                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                              otherButtonTitles:nil];
        [alert show];	
        [alert release];
        return NO;   
    }
    if(![genderLabel.text length] || [genderLabel.text isEqualToString:@"Geschlecht"])
    {
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:nil 
                              message:NSLocalizedString(@"Please enter your sex!",nil) 
                              delegate:nil 
                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                              otherButtonTitles:nil];
        [alert show];	
        [alert release];
        return NO;   
    }    
    if(![searchGenderLabel.text length] || [searchGenderLabel.text isEqualToString:@"Ich suche"])
    {
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:nil 
                              message:NSLocalizedString(@"Please enter your search gender!",nil) 
                              delegate:nil 
                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                              otherButtonTitles:nil];
        [alert show];	
        [alert release];
        return NO;   
    } 
    if(!acceptTACButton.isSelected)
    {
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:nil 
                              message:NSLocalizedString(@"Please read and accept the AGB and Privacy!", nil)
                              delegate:nil 
                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                              otherButtonTitles:nil];
        [alert show];	
        [alert release];
        return NO;    
    }
    return YES;
}

- (IBAction)submitButtonClick:(id)sender
{
    // hide keyboard
    [self hideKeyBoard];
    
    // validate form
    if (![self validateFields]) return;
    
    NSString *postString = [NSString stringWithFormat:@"op=register&username=%@&email=%@&password=%@&geschlecht=%@&suche=%@&ampel=%d&emailSub=%@&emailBody=%@", self.usernameTextField.text, self.emailTextField.text , self.passwordTextField.text, self.genderLabel.text, self.searchGenderLabel.text, trafficLightInt,NSLocalizedString(@"email_regis_subject", nil),NSLocalizedString(@"email_regis_body", nil)];
    
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];	
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.removeFromSuperViewOnHide = TRUE;
        HUD.delegate = self;
        [HUD show:YES];
    }
    [conn release];
}

- (void)showActionSheet1
{
    // hide keyboard first
    [self hideKeyBoard];
    
    // show action
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:nil
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:nil];
    [actionSheet addButtonWithTitle:@"Männlich"];
    [actionSheet addButtonWithTitle:@"Weiblich"];
    [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
    [actionSheet release];
}

- (void)genderLabelClick:(id)sender
{
    // hide keyboard first
    [self hideKeyBoard];
    
    // show action
    [self showActionSheet1];
    curentTargetControl = (UIControl *)genderLabel;
}

- (void)searchGenderLabelClick:(id)sender
{
    // hide keyboard first
    [self hideKeyBoard];
    
    // show action
    [self showActionSheet1];
    curentTargetControl = (UIControl *)searchGenderLabel;
}

- (void)agbLabelClick:(id)sender
{
    AGB *agb = [[AGB alloc] init];
    [self.navigationController pushViewController:agb animated:YES];
    [agb release];
}

- (void)privacyPolicyLabelClick:(id)sender
{
    PrivacyPolicy *privacyPolicy = [[PrivacyPolicy alloc] init];
    [self.navigationController pushViewController:privacyPolicy animated:YES];
    [privacyPolicy release];
}

-(NSMutableData *)generateDataFromText:(NSString *)dataText fieldName:(NSString *)fieldName
{
	NSString *post = [NSString stringWithFormat:@"\r\n--0xKhTmLbOuNdArY\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n", fieldName];
    // Get the post header int ASCII format:
    NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    
    // Generate the mutable data variable:
    NSMutableData *postData = [[[NSMutableData alloc] initWithLength:[postHeaderData length]] autorelease];
    [postData setData:postHeaderData];
    
	NSData *uploadData = [dataText dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	
    // Add the text:
    [postData appendData: uploadData];
    
    // Add the closing boundry:
    [postData appendData: [@"\r\n" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
    
    // Return the post data:
    return postData;
}

- (NSData *)generatePostDataForData:(NSData *)uploadData fileName:(NSString *)fileName
{
    // Generate the post header:
	
    NSString *post = [NSString stringWithFormat:@"\r\n--0xKhTmLbOuNdArY\r\nContent-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\nContent-Type: application/octet-stream\r\n\r\n", fileName];
    
    // Get the post header int ASCII format:
    NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    
    // Generate the mutable data variable:
    NSMutableData *postData = [[[NSMutableData alloc] initWithLength:[postHeaderData length]] autorelease];
    [postData setData:postHeaderData];
    
    // Add the image:
    [postData appendData: uploadData];
    
    // Add the closing boundry:
    [postData appendData: [@"\r\n--0xKhTmLbOuNdArY--" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
    
    // Return the post data:
    return postData;
}

-(UIImage *)resizeImage:(UIImage *)image:(NSInteger) width:(NSInteger) height 
{
	CGSize newSize = CGSizeMake(width, height);
    UIGraphicsBeginImageContext( newSize );
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)saveAvatarImage
{
    // check avatar image set
    if (!avatarIsChanged)
        return;
    
    NSData *imageData_ = UIImageJPEGRepresentation(self.avatarImageView.image, 1.0);
    
    NSString *urlString = [[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"];
    
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:urlString]];
	[request setHTTPMethod:@"POST"];
    
    NSMutableData *postData = [self generateDataFromText:@"upload" fieldName:@"op"];
    [postData appendData:[self generateDataFromText:self.usernameTextField.text fieldName:@"username"]];
    
    [postData appendData:[self generatePostDataForData:imageData_ fileName:@"speeddataimg.jpg"]];
    
    [request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];
	[request addValue:@"multipart/form-data; boundary=0xKhTmLbOuNdArY" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody: postData];
	// setting the body of the post to the reqeust
	[request setHTTPBody:postData];
    
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}

- (void)goBack
{
    // go home case
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"last_state"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    // pop to parent view controller
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Custom notifications

- (void)keyboardWillHide:(NSNotification *)noti
{    
    NSDictionary *userInfo = [noti userInfo];
    
    // restore size of scrollview
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.myScrollView setFrame:self.view.bounds];
    [UIView commitAnimations];
    
    keyboardIsShown = NO;
}
- (void)keyboardWillShow:(NSNotification *)noti
{
    // keyboard is already shown.
    if (keyboardIsShown) {
        return;
    }
    
    NSDictionary *userInfo = [noti userInfo];
    
    // get the size of the keyboard
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGFloat keyboardTop = keyboardRect.origin.y;
    CGRect newTextViewFrame = self.view.bounds;
    newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;
    
    // keyboard animation duration value
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    // resize the scrollview
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.myScrollView setFrame:newTextViewFrame];
    [UIView commitAnimations];
    
    keyboardIsShown = YES;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //NSLog(@"REGISTER -> viewDidLoad");
    
    // background
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    
    // scroll view
    [self.myScrollView setContentSize:CGSizeMake(320, 610)];
    
    // navigation title
    self.title = @"Registrierung";
    
    // navigation buttons
    UIButton *logoButton = [[UIButton alloc] initWithFrame:CGRectMake(0,2,35,35)];
    [logoButton setBackgroundImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal];
    UIBarButtonItem *iLButton = [[UIBarButtonItem alloc] initWithCustomView:logoButton];
    self.navigationItem.leftBarButtonItem = iLButton;
    [logoButton release];
    [iLButton release];
    
    UIButton *backButton = [UIButton buttonWithType:100];
    [backButton setTitle:@"Zurück" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iRButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];
    self.navigationItem.rightBarButtonItem = iRButton;
    [iRButton release];
    
    // gender label
    UITapGestureRecognizer *tgrGenderLabel = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(genderLabelClick:)] autorelease];
    [self.genderLabel addGestureRecognizer:tgrGenderLabel];
    
    // searchgender label
    UITapGestureRecognizer *tgrSearchGenderLabel = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(searchGenderLabelClick:)] autorelease];
    [self.searchGenderLabel addGestureRecognizer:tgrSearchGenderLabel];
    
    // agb label
    UITapGestureRecognizer *tgrAGBLabel = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(agbLabelClick:)] autorelease];
    [self.agbLabel addGestureRecognizer:tgrAGBLabel];
    
    // privacy policy label
    UITapGestureRecognizer *tgrPrivacyPolicyLabel = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(privacyPolicyLabelClick:)] autorelease];
    [self.privacyPolicyLabel addGestureRecognizer:tgrPrivacyPolicyLabel];
    
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification 
                                               object:self.view.window];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillHide:) 
                                                 name:UIKeyboardWillHideNotification 
                                               object:self.view.window];
    keyboardIsShown = NO;
    
    // default traffic light
    [self lightRedButtonClick:nil];
    
    [super viewDidLoad];
}

- (void)viewDidUnload
{
    //NSLog(@"REGISTER -> viewDidUnload");
    [self cleanup];
    
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillShowNotification 
                                                  object:nil]; 
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillHideNotification 
                                                  object:nil]; 
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    //NSLog(@"REGISTER -> viewWillAppear");
    //NSLog(@"REGISTER -> viewControllers: %@", self.navigationController.viewControllers);
    
    // save state
    [AppDelegate saveState:0 withViewController:self];
    
    // navigation bar
    self.navigationController.navigationBar.hidden = NO;
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
    self.avatarImageView.image = [self resizeImage:img :55 :55];
    avatarIsChanged = YES;
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{
    [textField resignFirstResponder];
    [self submitButtonClick:NULL];
	return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField 
{
    BOOL isHideNav = self.navigationController.navigationBarHidden;
    [self.myScrollView setContentOffset:CGPointMake(0, textField.frame.origin.y/2 + (isHideNav ? 0 : 44)) animated:YES];
}

#pragma mark - 
#pragma mark - ActionSheet Delegate

- (void)actionSheet:(UIActionSheet *)menu didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    if ([curentTargetControl isKindOfClass:[UIButton class]]) {
        // open dialog
        if (buttonIndex == 0) return;
        
        UIImagePickerController * picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;    
        switch (buttonIndex) {
            case 1:
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            case 2:
                picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                break;
            case 3:
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
            default:
                break;
        }
        picker.allowsEditing = TRUE;
        [self presentModalViewController:picker animated:YES];
        [picker release];
    }
    else {
        switch (buttonIndex) {
            case 0:
                [(UILabel *) curentTargetControl setText:@"Männlich"];
                break;
            case 1:
                [(UILabel *) curentTargetControl setText:@"Weiblich"];
                break;
            default:
                break;
        }
        [(UILabel *) curentTargetControl setTextColor:[UIColor blackColor]];
    }
}

#pragma mark -
#pragma mark NSURLConnectionDelegete

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[responseData setLength:0];
    
    // loading
	HUD.mode = MBProgressHUDModeDeterminate;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
    // loading
    [HUD hide:YES];
    
    /* Error message */
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
													message:NSLocalizedString(@"Unknown network error", nil)
												   delegate:self 
										  cancelButtonTitle:NSLocalizedString(@"OK", nil) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];	
    
    [responseData release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	
	NSMutableDictionary *results = [responseString JSONValue];
    //NSLog(@"%@", results);
    NSString *status = [results objectForKey:@"status"];
    if ([status isEqualToString:@"1"])
    {
        @try {
            [self saveAvatarImage];
        }
        @catch (NSException *ex){
            //NSLog(@"Exception: %@", ex);
        }
        
        // set auto login
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"auto_login"];
        [[NSUserDefaults standardUserDefaults] setValue:usernameTextField.text forKey:@"username"];
        [[NSUserDefaults standardUserDefaults] setValue:passwordTextField.text forKey:@"password"];
        [self.navigationController popToRootViewControllerAnimated:NO];
    }
    else if([status isEqualToString:@"-1"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                                                        message:NSLocalizedString(@"Register failure - exist an account!", nil)
                                                       delegate:self 
                                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    else 
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                                                        message:NSLocalizedString(@"Register failure!", nil)
                                                       delegate:self 
                                              cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    
    // loading
    [HUD hide:YES];
    
    [responseData release];
	[responseString release];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    //[HUD removeFromSuperview];
    [HUD release];
    HUD = nil;
}

@end
